package com.ycrlkj.android.modulespublic.common.net.transformer;

import androidx.annotation.NonNull;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.response.MResponse;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class ResponseTransformer<T> implements ObservableTransformer<MResponse<T>, T> {

    private CompositeDisposable compositeDisposable;

    public ResponseTransformer() {}

    public ResponseTransformer(CompositeDisposable compositeDisposable) {
        this.compositeDisposable = compositeDisposable;
    }

    public static <U> ResponseTransformer<U> obtain() {
        return new ResponseTransformer<>();
    }

    public static <U> ResponseTransformer<U> obtain(CompositeDisposable compositeDisposable) {
        return new ResponseTransformer<>(compositeDisposable);
    }

    @Override
    public ObservableSource<T> apply(Observable<MResponse<T>> upstream) {
        return upstream
                //生命周期管理
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (compositeDisposable != null) {
                            compositeDisposable.add(disposable);
                        }
                    }
                })
                //错误处理
                .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends MResponse<T>>>() {
                    @Override
                    public ObservableSource<? extends MResponse<T>> apply(Throwable throwable) throws Exception {

                        // 出现异常后统一处理
                        return Observable.error(ApiException.exception2ApiException(throwable));

                    }
                })
                //json转换
                .flatMap(new Function<MResponse<T>, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(@NonNull MResponse<T> response) throws Exception {

                        return new ResponseDataHandler<T>(response).doWith();

                    }
                })
                //切到io线程
                .subscribeOn(Schedulers.io())
                //切到主线程
                .observeOn(AndroidSchedulers.mainThread());
    }
}
